package com.sfc.spiderweb.util;

import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
    private static int readTimeOut = 60000;  //60000毫秒
    private static int connectTimeout = 15000; //15000毫秒

    /**
     * 原生的方式性能比较好，采用get请求
     *
     * @param url
     * @return
     */
    public static String doGet(String url) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = "";

        try {
            URL urlStr = new URL(url);
            connection = (HttpURLConnection) urlStr.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(connectTimeout);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(readTimeOut);

            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.lineSeparator());
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }
        return result;
    }

    /**
     * 原生的方式性能比较好
     *
     * @param httpUrl
     * @param param   json 串
     * @param type    PUT,POST,DELETE  其中之一
     * @return
     */
    public static String doPost(String httpUrl, String param, String type) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;

        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();

            // 设置连接请求方式
            if (StringUtils.isEmpty(type)) {
                connection.setRequestMethod("POST");
            } else if (type.toUpperCase().equals("POST")) {
                connection.setRequestMethod("POST");
            } else if (type.toUpperCase().equals("DELETE")) {
                connection.setRequestMethod("DELETE");
            } else {
                connection.setRequestMethod("PUT");
            }
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(connectTimeout);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(readTimeOut);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);

//            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
//            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Type", "application/json");

//            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");

            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            if (!StringUtils.isEmpty(param)) {
                os.write(param.getBytes());
            }
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp + System.lineSeparator());
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (Exception e) {
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (Exception e) {
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

    public static void main(String[] args) {
        long b = System.currentTimeMillis();
        System.out.println(b);
        String result = doGet("http://190.168.0.77:9000/position/get/221");
        System.out.println(result);
        long e = System.currentTimeMillis();
        System.out.println(e);
        System.out.println(e - b);
        System.out.println("--------------------------------");

        //============post data========
        String x = "{\"createTime\": \"2019-10-03 10:40:36\",\n" +
                "  \"description\": \"string\",\n" +
                "  \"ip\": \"10.10.10.10\",\n" +
                "  \"ulId\": -1,\n" +
                "  \"url\": \"url\",\n" +
                "  \"usId\": 1,\n" +
                "  \"userId\": 1,\n" +
                "  \"username\": \"ddstring\"\n" +
                "}";

        b = System.currentTimeMillis();
        System.out.println(b);
        result = doPost("http://190.168.0.77:9000/userlog/add", x, "post");
        System.out.println(result);
        e = System.currentTimeMillis();
        System.out.println(e);
        System.out.println(e - b);

        System.out.println("--------------------------------");

        //============put data========
        x = "{\n" +
                "  \"ucId\": 137,\n" +
                "  \"ucName\": \"test\",\n" +
                "  \"ucParentId\": 123\n" +
                "}";
        b = System.currentTimeMillis();
        System.out.println(b);
        result = doPost("http://190.168.0.77:9000/company/update", x, "put");
        System.out.println(result);
        e = System.currentTimeMillis();
        System.out.println(e);
        System.out.println(e - b);
        System.out.println("--------------------------------");

        //============delete data========
        b = System.currentTimeMillis();
        System.out.println(b);
        result = doPost("http://190.168.0.77:9000/customDepartment/delete/9", null, "delete");
        System.out.println(result);
        e = System.currentTimeMillis();
        System.out.println(e);
        System.out.println(e - b);
    }
}

